import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TablesService} from '../../services/tables.service';
import {SaveStateService} from '../../services/save-state.service';
import {SelectionService} from '../../services/selection.service';

@Component({
  selector: 'app-table-list',
  standalone: true,
  imports: [CommonModule],
  templateUrl: './table-list.component.html',
  styleUrls: ['./table-list.component.css']
})
export class TableListComponent {
  tablesService = inject(TablesService);
  saveStateService = inject(SaveStateService);
  selectionService = inject(SelectionService);

  editTable(id: string) {
    console.log('编辑表格:', id);
    this.selectionService.selectTable(id);
  }

  deleteTable(id: string) {
    this.tablesService.removeTable(id);
    this.saveStateService.markUnsaved();
  }

  createTable() {
    const newTable = {
      id: `table_${Date.now()}`,
      name: '新表格',
      x: 100,
      y: 100,
      fields: [
        {
          id: `field_${Date.now()}`,
          name: 'id',
          type: 'INTEGER',
          primaryKey: true,
          notNull: true,
          increment: true
        }
      ]
    };
    this.tablesService.addTable(newTable);
    this.saveStateService.markUnsaved();
  }

  addField(tableId: string) {
    const newField = {
      id: `field_${Date.now()}`,
      name: '新字段',
      type: 'VARCHAR(255)',
      notNull: false
    };
    this.tablesService.addField(tableId, newField);
    this.saveStateService.markUnsaved();
  }

  isTableSelected(tableId: string): boolean {
    return this.selectionService.selection().selectedTables.includes(tableId);
  }
}
